#coding:utf-8
'''
create on 2017-05-06
@author:sandy
'''

import logging
from pycommon import Const
from pycommon import Pack as packet
from pycommon import Utils
import UserManager
import CreateTableConfig
import TableManager
import CenterBuild
import HallInfoManager
import GameFactory
import CenterCtxManager


def cmdUserLogin(gate,uid,pid,pkt):
    session,cvr,partner = packet.unpack("sHH",pkt)
    logging.debug("cmdUserLogin uid=%d pid=%d session=%s,cvr=%d,partner=%d",uid,pid,session,cvr,partner)
    UserManager.instance.onUserLogin(gate.getSId(),uid,pid,session,cvr,partner)
    pass

def cmdUserLoginWeChat(gate,uid,pid,pkt):
    session,nickname,headimgurl,sex,cvr,partner = packet.unpack("ssSBHH",pkt)
    logging.debug("cmdUserLoginWeChat uid=%d pid=%d session=%s,nickName=%s,headimgurl=%s,sex=%d,cvr=%d,partner=%d",uid,pid,session,Utils.pstr2u(nickname),headimgurl,sex,cvr,partner)
    UserManager.instance.onUserLogin(gate.getSId(),uid,pid,session,cvr,partner,Utils.pstr2u(nickname),headimgurl,sex)
    pass

def cmdCreateTable(gate,uid,pid,pkt):
    user = UserManager.instance.getUser(uid)
    if not user:
        logging.warn(u'cmdCreateTable(), no user, uid=%d', uid)
        return
    #gameIndex 标记游戏
    #tableModel 4人桌子
    #maxRound  最大轮数
    #playModel 玩法模式
    #CardId 房卡ID
    gameIndex,tableModel,maxRound,playModel,cardId = packet.unpack("HHHHI",pkt);
    logging.debug(u"uid=%d request createTable:%d,%d,%d,%d",uid,gameIndex,maxRound,tableModel,playModel);
    code = Const.ERR_OK
    needCard = 0
    for i in range(1):
        cardNum = user.getPropById(cardId)
        check = CreateTableConfig.instance.checkTableModel(tableModel)
        if not check:
            logging.debug(u"uid=%d tableModel=%d Error",uid,tableModel)
            code = Const.ERR_MJ_CREATETABLE_TABLEMODEL
            break
        check = CreateTableConfig.instance.checkMaxRound(tableModel,maxRound)
        if not check:
            logging.debug(u"uid=%d maxRound=%d Error",uid,maxRound)
            code = Const.ERR_MJ_CREATETABLE_MAXROUND
            break
        needCard = CreateTableConfig.instance.getNeedCards(tableModel,maxRound)
        if cardNum < needCard:
            logging.debug(u"uid=%d roomCard cardId=%d not enough %d",uid,cardId,cardNum)
            code = Const.ERR_MJ_CREATETABLE_CARDNOTENOUGH
            break
        check = CreateTableConfig.instance.checkPlayModel(playModel)
        if not check:
            logging.debug(u"uid=%d playModel=%d Error",uid,playModel)
            code = Const.ERR_MJ_CREATETABLE_PLAYMODEL
            break
        
        isInTable = TableManager.instance.userIsInTable(uid)
        if isInTable:
            logging.debug(u"uid=%d already in table",uid)
            code = Const.ERR_MJ_USER_HASINTABLE
            break
        
    if code != Const.ERR_OK:
        gate.transPkt2Client(uid,CenterBuild.sendCreateTableToClient(code,""))
        return
    if gameIndex == 1:
        suit = HallInfoManager.instance.choseSuitableGameAndHallId(tableModel)
        if suit != None:
            gamesid = suit.get("sid")
            hallId = suit.get("hid")
            game = GameFactory.instance.getGameSrvBySid(gamesid)
            tableIdStr = TableManager.instance.create6SNum()
            TableManager.instance.createTable(tableIdStr)
            ctxid = CenterCtxManager.instance.addCtx(uid,gate.getSId(),maxRound,tableModel,playModel,cardId,needCard,hallId,tableIdStr)
            game.sendPacket(CenterBuild.sendCreateTableToGame(ctxid,uid,maxRound,hallId,playModel,tableIdStr))
        else:
            logging.debug(u"no used game server")
            gate.transPkt2Client(uid,CenterBuild.sendCreateTableToClient(Const.ERR_MJ_NO_GAMESERVER,""))
    else:
        logging.debug(u"game index error")
    pass

def cmdEnterTable(gate,uid,pid,pkt):
    tableIdStr = packet.unpack("s",pkt)
    c = TableManager.instance.canEnterTable(tableIdStr,uid)
    if c == Const.ERR_OK:
        table = TableManager.instance.getTableByTableIdStr(tableIdStr)
        logging.debug("uid=%d request enter tableId = %s Sucess",uid,tableIdStr)
        gate.transPkt2Client(uid,CenterBuild.sendEnterTableToClient(c,table.gameIp,table.gamePort,table.tableId,table.hallId))
    else:
        logging.debug("uid=%d request enter tableId = %s Failed errorId = %d",uid,tableIdStr,c)
        gate.transPkt2Client(uid,CenterBuild.sendEnterTableToClient(c,"",0,0,0))
    
    pass

#===========================================================================
    
__cmdTable = {
                Const.CMD_C2CT_USER_LOGIN        : cmdUserLogin,
                Const.CMD_C2CT_USER_LOGIN_WECHAT : cmdUserLoginWeChat,
                Const.CMD_C2CT_CREATE_TABLE      : cmdCreateTable,
                Const.CMD_C2CT_ENTER_TABLE       : cmdEnterTable
             } 

def parse(gate,uid,pid,cmd,pkt):
    logging.debug(u"GateSid = %d uid = %d ClientParse cmd = %d",gate.getSId(),uid,cmd)
    func = __cmdTable.get(cmd)
    if not func :
        logging.error("cmd is not exit");
    func(gate,uid,pid,pkt)    
    
if __name__ == '__main__':
    pass